package com.atguigu.tingshu.album.service.impl;


import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Override
    public Map<String, String> uploadTrack(MultipartFile trackFile) {
        try {
            /*
            * 使用云 API 密钥初始化 VodUploadClient 实例。
            * */
            String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), trackFile);
            VodUploadClient client
                    = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //创建请求对象
            VodUploadRequest request = new VodUploadRequest();
            request.setMediaFilePath(tempPath);

            //调用云点播客户端上传文件
            VodUploadResponse uploadResponse = client.upload(vodConstantProperties.getRegion(), request);
            //判断返回结果是否为空,不为空获取返回结果中的音频文件的唯一标识，还有在线地址
            if (uploadResponse!=null){
                //创建返回对象
                Map<String,String> tarckResponseMap = new HashMap<>();
                //获取返回结果中的数据并封装进返回结果
                tarckResponseMap.put("mediaFileId",uploadResponse.getFileId());
                tarckResponseMap.put("mediaUrl", uploadResponse.getMediaUrl());
                return tarckResponseMap;
            }
            return null;
        } catch (Exception e) {
            log.error("[专辑服务]音频文件上传异常：{}", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据音频文件唯一标识获取音频详情信息
     *
     * @param mediaFileId 文件唯一标识
     * @return
     */
    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId) {
        try {
            //1. 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化媒体详情client对象
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFileId};
            req.setFileIds(fileIds1);
            //4.发起请求获取音频文件详情-返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            //5.解析获取音频文件详情
            TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
            if (resp != null) {
                MediaInfo mediaInfo = resp.getMediaInfoSet()[0];
                //5.1 获取音频文件基本信息-获取文件类型
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                String type = basicInfo.getType();
                trackMediaInfoVo.setType(type);
                //5.2 获取音频文件元信息-获取文件时长、大小
                MediaMetaData metaData = mediaInfo.getMetaData();
                Float audioDuration = metaData.getAudioDuration();
                trackMediaInfoVo.setDuration(audioDuration);
                Long size = metaData.getSize();
                trackMediaInfoVo.setSize(size);
                //5.3 腾讯云点播暂未提供审核状态的返回值
            }
            return trackMediaInfoVo;
        } catch (Exception e) {
            log.error("[专辑服务]获取点播服务平台文件信息异常：{}", e);
            throw new GuiguException(500, "获取点播服务平台文件信息异常" + e.getMessage());
        }
    }

    @Override
    public void deleteMedia(String mediaFileIdBefore) {
        try{
            log.info("--------------"+Thread.currentThread().getName());
            //1. 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileIdBefore);
            //4.执行删除资源请求，返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            client.DeleteMedia(req);
        } catch (Exception e) {
            log.error("[专辑服务]删除点播平台资源异常：{}", e);
        }
    }
}
